<template>
    <div :class="{'container':true}">
        <page-table :func="func" ref="pt" v-bind="$route.query" :props="{ref:'table'}"
        v-if="status!=0"
		@selectChange="selectChange"
        >
           <template v-slot:orderText>
                <div class="orderText">
                    订单导入
                </div>
            </template>
			<template v-slot:shopName="{data}">
				<div>
					<div v-if="!data.row.isEdit" @dblclick="dbclick(data.row)">
						{{data.row.shopName}}
					</div>
					<div v-else  style="display:flex">
						<el-input ref="shopNameEdit"  size="mini" v-model="currentEditShopName" @blur="cancelEditShopName(data.row)"  @change="confirmEdit(data.row)"></el-input>
						<el-link type="primary"  @click="cancelEditShopName(data.row)">取消</el-link>
					</div>
				</div>
			</template>
			<template v-slot:total>
				总金额1({{ afterParse.totalPrice }})
			</template>
			<template v-slot:platform>
				来源 
			</template>
			<template v-slot:count>
				订单数({{ afterParse.orderCount }})
			</template>
            <template v-slot:expand="{data}">
				<div v-if="data.row.imgList.length==0">
					暂无订单截图
				</div>
				<div v-viewer class="expand-img-container" v-else> 
					<img :src="item | getFilePath" alt="" v-for="item in data.row.imgList" :key="item" width="50px" height="50px">
				</div>
			</template> 
            <template v-slot:moreoperation="{data}">
                <el-button @click="batchPrice(data)" type="danger" size="small" v-if="status==1">批量改价</el-button>
                <el-button @click="ImportToSystem(data)" :type="data.row.isClick?'info':'warning'" size="small" v-if="status==1">导入</el-button>
                <el-button type="primary" size="small" @click="editForShop(data)" v-if="status==1">编辑</el-button>
            </template>
            <template v-slot:back="{data}">
                <el-button v-if="status!=0" @click="back" size="mini">返回</el-button>
            </template>
            <template v-slot:addBtn2="{data}">
                <el-button type="primary" size="mini" v-if="status!=0" @click="add">添加</el-button>
            </template>
			<template v-slot:errlog>
				<!-- <div v-html="errorLogString" class="errorLogString">
					
				</div> -->
			</template>
			<template v-slot:batchChangePrice>
                <el-button type="danger" :disabled="checkBoxNoChange" size="mini" v-if="status==1" @click="showBatchChange=true">批量改价</el-button>
			</template>
            <template v-slot:batchAddbtn>
                <el-button type="warning" size="mini" v-if="status==1" @click="batchAdd">一键导入</el-button>
            </template>
			<template v-slot:prices="{data}">
				<div>
					<span v-for="(item,index) in data.row.prices" :key="index">
						{{ item }}{{ (data.row.prices.size>0&&index!=data.row.prices.size-1)?',':'' }}
					</span>
				</div>
			</template>
        </page-table>
        <div class="file-upload-container" v-if="status==0">
            <el-upload
                ref="upload"
                action="/"
                drag
				multiple
                accept=".xlsx, .xlsm, .xls"
                :auto-upload="false"
                :on-change="handleChange"
				show-file-list>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传excel文件</div>
            </el-upload>
            <div class="begin-btn">
                <el-button type="primary" @click="begin" :disabled="!hasFile" v-if="status==0">开始解析</el-button> 
            </div>
        </div>
        <el-dialog
                :title="title" 
				v-model="visible"
				:visible.sync="visible"
                width="30%">
				<div style="margin-bottom: 10px;display: flex;justify-content: space-between;">
					 <div>
							价格：
						<span v-for="(item,index) in shopArrs[currentShop]?.prices" :key="item">
							{{ item }}{{ index != shopArrs[currentShop]?.prices?.size-1?",":"" }}
						</span>
					 </div>
					 <div>
						总价格:{{ shopArrs[currentShop]?.total }}
					 </div>
				</div>
					<div v-for="(item,index) in changeForm" :key="item.price1">
						<el-form ref="changPrice" :model="item" inline >
							<el-form-item label="" prop="price1">
								<el-input type="number" clearable v-model="item.price1" placeholder="原金额"></el-input>
								<!-- <el-input v-model="form.name"></el-input> -->
							</el-form-item>
							<el-form-item label="" prop="price2">
								<el-input ref="price2" type="number" clearable v-model="item.price2" placeholder="替换金额" @change="changePrice(index)"></el-input>
							</el-form-item>
						</el-form>
						<!-- <div style="display:flex" ref="changPrice">
							<el-input type="number" clearable v-model="item.price1" placeholder="原金额" @change="changePrice(index)"></el-input>
							<el-input type="number" clearable v-model="item.price2" placeholder="替换金额" @change="changePrice(index)"></el-input>
						</div> -->
						<!-- <json-form
							direction="h"
							ref="changPrice"
							:options="changeOptions"
							:form="item"
							v-if="visible"
							:index="index"
						>
						</json-form> -->
						<!-- {{ index }} -->
					</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="visible = false">关闭</el-button>
                <!-- <el-button type="danger" @click="confirmChangePrince">修改价格</el-button> -->
            </span>	
        </el-dialog>
        <el-dialog
            title="新增"
            v-model="showShopAdd"
            :visible.sync="showShopAdd"
            >
            <json-form
                direction="h"
                ref="addShopForm"
                :options="addShopOption"
                v-if="showShopAdd">

            </json-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showShopAdd = false">取 消</el-button>
			    <el-button type="primary" @click="addShopHandle">确 定</el-button>
            </span>
        </el-dialog>
		<el-dialog
			title="批量计算金额"
			v-model="showBatchChange"
			:visible.sync="showBatchChange"
			>
			<json-form ref="batchChangeRef" :form="batchChangePriceForm" :options="batchChangePriceOptions">

			</json-form>
			<span slot="footer" class="dialog-footer">
                <el-button @click="showBatchChange = false">取 消</el-button>
			    <el-button type="primary" @click="batchChange">确 定</el-button>
            </span>
		</el-dialog>
		<div v-html="errorLogString" class="errorLogString">
					
		</div>
    </div>
</template>
<script>
import pageTable from "@/components/page-table.vue"
import ImagePreview from "@/components/image-preview.vue"
import func from "./index.js"
import {TypeOptions} from "../constant"
import {readFile} from "@/util/fileUtil.js"
import {cnKeyJson2en,columns,importToSys} from "./format"
import * as XLSX from "xlsx"
import NP from "number-precision"
import jsonForm from "@/components/json-form.vue"
import { getDateDetail } from "@/util/date"
import {getOptions} from "@/apis/order/index"
import { getShopOPtions,getUrl } from "@/apis/shop"
import store from "@/store/index"
import { success } from "@/util/notice"
export default {
	name:"billImport",
	components:{
		pageTable,
		ImagePreview,
		jsonForm
	},
	data(){
		let that = this
		return {
			func,
			TypeOptions,
			importArrs:[],
			hasFile:false,
			status:0,
			currentShop:0,
			shopArrs:[],
			visible:false,
			changeForm:[],
			changeOptions:[
				{
					key:"price1",
					label:"",
					type:"el-input",
					// width:"100px",
					required:true,
					props:{
						type:"number",
						placeholder:"原金额",
						clearable:true
					}
				},
				{
					key:"price2",
					label:"",
					type:"el-input",
					required:true,
					// width:"100px",
					ref:"price2",
					props:{
						type:"number",
						placeholder:"替换金额",
						clearable:true,

					},
					listeners:{
						
					}
				},
			],
			showShopAdd:false,
			addShopOption:[
				{
					key:"shopName",
					type:"el-input",
					label:"店铺名",
					required:true
				},
				{
					key:"platform",
					type:"el-select",
					label:"所属平台",
					options:TypeOptions,
					required:true
				}
			],
			shopForm:{
				price1:"",
				price2:""
			},
			typeInfo:{},
			errlogs:[],
			checkBoxNoChange:true,
			showBatchChange:false,
			batchChangePriceForm:{
				price:""
			},
			batchChangePriceOptions:[
				{
					key:"price",
					type:"el-input",
					label:"在原来的基础上计算的金额",
					required:true,
					props:{
						type:"number"
					}
				},
			],
			rules:{"price1":[{"required":true,"trigger":"blur"}],"price2":[{"required":true,"trigger":"blur"}]},
			genBidObj:{},
			currentEditShopName:"",
		}
	},
	methods:{
		handleChange(file){
			console.log(file)
			this.hasFile = this.$refs.upload.uploadFiles.length>0
		},
		async begin(){
			let files = this.$refs.upload.uploadFiles
			console.log(files)
			for(let i = 0;i<files.length;i++){
				let dataBinary = await readFile(files[i].raw)
				let workBook = XLSX.read(dataBinary, { type: "binary", cellDates: true })
				let workSheet = workBook.Sheets[workBook.SheetNames[0]]
				// console.log(workSheet)
				// console.log(workSheet)
				// const data = XLSX.utils.sheet_to_json(workSheet,{header:1,range:1})
				const data = XLSX.utils.sheet_to_json(workSheet,{raw:false})
				console.log("默认解析的json:",data)//这里已经能拿到转换后的json
				let res = cnKeyJson2en(data)
				console.log("转换后的json:",res)//这里已经能拿到转换后的json
				this.importArrs = this.importArrs.concat(res)
			}
			this.status = 1
			this.getBeforeParseTotal()
			this.autoGenBid()
			this.filterData()
		},
		getBeforeParseTotal(){
			let res = this.importArrs.reduce((current,next)=>{
				if(!next.orderNo){
					return {
						totalPrice:current.totalPrice,
						orderCount:current.orderCount
					}
				}
				return {
					totalPrice:NP.plus(current.totalPrice,next.money),
					orderCount:NP.plus(current.orderCount,1)
				}
			},{
				totalPrice:0,
				orderCount:0
			})
			this.errlogs.push(`转换前的数据，总金额:${res.totalPrice},订单数:${res.orderCount}`)
			console.log(res)
		},
		autoGenBid(){
			let genBidObj = {}
			
			this.importArrs.forEach(item=>{
				if(item.orderId){
					genBidObj[item.shopName] || (genBidObj[item.shopName] = {})
					if(item.bid){
						genBidObj[item.shopName][item.platform] || (genBidObj[item.shopName][item.platform]=item.bid)
					}else{
						genBidObj[item.shopName][item.platform] || (genBidObj[item.shopName][item.platform]=item.orderId)
					}
				}
			})
			console.log(genBidObj)
			this.genBidObj = genBidObj
			this.importArrs = this.importArrs.map(item=>{
				if(!item.bid&&item.orderId){
					item.bid = this.genBidObj[item.shopName][item.platform]
				}
				return item
			})
		},
		/**
		 * 获取列表中唯一的platform值，并返回一个格式化的字符串
		 * @param {Array} list - 包含platform字段的列表
		 * @returns {string} - 格式化后的platform字符串，如果有多个则用'&'连接
		 */
		getUniquePlatforms(list) {
			// 使用Set收集唯一的platform值
			const uniquePlatforms = new Set(list.map(item => item.platform).filter(platform => platform)); 
			// 根据Set的大小构建结果字符串
			return uniquePlatforms.size === 1 ? uniquePlatforms.values().next().value : [...uniquePlatforms].join('&');
		},
		async filterData(){
			console.log("导入的所有数据:",this.importArrs)
			//过滤出店铺
			let shopObj = {}
			let typeInfo = {}
			this.importArrs = this.importArrs.reduce((accumulator, current) => {
				const duplicate = accumulator.find(item => item.orderId === current.orderId || item.orderNo === current.orderNo)
				// current.shopName = current.shopName.replaceAll("（","(").replaceAll("）",")")
				if(!current.orderNo){
					return accumulator
				}
				if (!duplicate) {
					typeInfo[current.shopName] || (typeInfo[current.shopName]=new Set())
					shopObj[current.shopName] || (shopObj[current.shopName] = {})
					shopObj[current.shopName].shopName = current.shopName
					shopObj[current.shopName].platform = current.platform
					shopObj[current.shopName].orderList || ( shopObj[current.shopName].orderList = [])
					shopObj[current.shopName].orderList.push(current)
					shopObj[current.shopName].prices || (shopObj[current.shopName].prices = new Set())
					shopObj[current.shopName].prices.add(current.money)
					typeInfo[current.shopName].add(current.platform)
					shopObj[current.shopName].isClick = false
					shopObj[current.shopName].isEdit = false
					return accumulator.concat([current])
				}else{
					this.errlogs.push(`发现重复的订单,订单id:${current.orderId},订单号:${current.orderNo},店铺名:${current.shopName},平台:${current.platform}。在${duplicate.shopName}有重复的订单id/订单号`)
				}
				return accumulator
			}, [])
			this.typeInfo = typeInfo
			// console.log(this.importArrs)
			console.log(typeInfo)
			for (const key in shopObj) {
				shopObj[key].total = shopObj[key].orderList.reduce((pre,next)=>{
					return NP.plus(pre,next.money)
				},0)
				shopObj[key].count = shopObj[key].orderList.length
				shopObj[key].platform = this.getUniquePlatforms(shopObj[key].orderList)
			}
			console.log("店铺数量",shopObj)
			this.shopArrs = Object.values(shopObj)
            
			this.$message.success("解析到"+this.shopArrs.length+"个店铺，"+this.importArrs.length+"条数据")
            
			setTimeout(()=>{
				let pt = this.$refs.pt
				pt.tableData = this.shopArrs
				pt.config.table.show = true
				pt.columns = columns["shop"]
				pt.config.operation.show = true
			})
			
		},
		editForShop(data){
			console.log(data)
			this.currentShop = data.$index
			this.status = 2  
		},
		back(){
			if(this.status==2){
				this.status = 1
			}else if(this.status == 1){
				this.status = 0
			}
		},
		batchPrice(data){
			console.log(data)
			let prices = Array.from(data.row.prices)
			this.changeForm = prices.map(item=>{
				return {
					price1:item,
					price2:null	
				}
			})
			this.visible = true
			this.currentShop = data.$index
		},
		confirmChangePrince(){
			// console.log(this.$refs.changPrice)
			let copm = this.$refs.changPrice
			let success = 0
			// console.log(copm)
			for(let i=0;i<copm.length;i++){
				copm[i].submit((form)=>{
					console.log("通过验证,",form)
					let pass = 0
					//改价，等于form.price1 的改成 form.price
					this.shopArrs[this.currentShop].orderList = this.shopArrs[this.currentShop].orderList.map(item=>{
						Number(item.money) == Number(form.price1) && pass++
						return {
							...item,
							money:Number(item.money)==Number(form.price1)?form.price2:item.money
						}
					})
					if(pass==0){
						this.$message.error(`未找到与 ${form.price1} 匹配的金额`)
						return
					}
					success++
					this.updateCount()
					this.$refs.pt.tableData = this.shopArrs
					// this.visible = false
					let prices = Array.from(this.shopArrs[this.currentShop].prices)
					this.changeForm = prices.map(item=>{
						return {
							price1:item,
							price2:null
						}
					})
				})
			}
			console.log(success)
			if(success==copm.length){
				this.visible = false
			}
		},
		async add(){
			if(this.status==1){
				this.showShopAdd = true
			}else if(this.status == 2){
				getOptions().then(res=>{
					console.log(res)
					store.commit("option/setBillOption",res.data)
				})
				getShopOPtions().then(res=>{
					store.commit("option/setShopOPtion",res.data)
				})
				let that = this.$refs.pt
				// that.addFun && that.addFun instanceof Function && that.addFun(...e)
				that.updateField = await that.addFieldMethod({
					bid:that.search.form.billNo,
					orderCreateTime:getDateDetail(),
					shopName:this.shopArrs[this.currentShop].shopName
				})
				that.mode = "add"
				that.show = true
			}
		},
		addShopHandle(){
			this.$refs.addShopForm.submit((form)=>{
				let obj = {
					shopName:form.shopName,
					platform:TypeOptions.find(item=>item.value==form.platform).label,
					count:0,
					total:0,
					orderList:[]
				}
				console.log(form)
				this.typeInfo[form.shopName] = new Set()
				this.typeInfo[form.shopName].add(obj.platform)
				this.shopArrs.push(obj)
				this.$refs.pt.tableData = this.shopArrs
				this.showShopAdd  = false
                
			})
		},
		updateCount(){
			//更新总额
			this.shopArrs = this.shopArrs.map(item=>{
				let set = new Set()
				let total = item.orderList.reduce((prev,next)=>{
					set.add(NP.plus(next.money,0))
					return NP.plus(prev,next.money)
				},0)
				return {
					...item,
					total:total,
					count:item.orderList.length,
					prices:set
				}
			})
			this.$refs.pt.tableData = this.shopArrs


		},
		async ImportToSystem(data){
			await this.$confirm("将导入当前订单到系统，是否继续", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
			this.currentShop = data.$index
			let shop = this.shopArrs[data.$index]
			let types = this.typeInfo[shop.shopName]
			let shopObj = {
				shopName:shop.shopName,
				platform:TypeOptions.find(type=>type.label==shop.platform||type.value == shop.platform).value
			}
			let billObj = {}
			shop.orderList.forEach(item=>{
				let platform = TypeOptions.find(type=>type.label==item.platform||type.value == item.platform).value
			 
				billObj[item.bid] = {
					activeDate:item.activeDate,
					billNo:item.bid,
					shopName:item.shopName,
					platform:TypeOptions.find(type=>type.label==item.platform||type.value == item.platform).value
				}
			})
			let shops = []
			types.forEach(item=>{
				let obj = {
					shopName:shop.shopName,
					platform:TypeOptions.find(type=>type.label==item||type.value == item).value
				}
				shops.push(obj)
			})
			// console.log(billObj,'billObj')
			let bills = Object.values(billObj)
			console.log(shops,bills)
			// let shops = this.typeInfo[]
			try {
				await importToSys(shops,bills,shop.orderList)

				data.row.isClick = true
			} catch (error) {
				console.log(error)
				this.errlogs.push(shop.shopName+":"+error.message || error)

			}			
		},
		async batchImport(){
			for(let i=0;i<this.shopArrs.length;i++){
				let shop = this.shopArrs[i]
				let types = this.typeInfo[shop.shopName]
				let billObj = {}
				shop.orderList.forEach(item=>{
					billObj[item.bid] = {
						activeDate:item.activeDate,
						billNo:item.bid,
						shopName:item.shopName,
						platform:TypeOptions.find(type=>type.label==item.platform||type.value == item.platform).value
					}
					item.platform = item.platform.includes("美团") ? 1 : 2
				})
				let shops = []
				types.forEach(item=>{
					let obj = {
						shopName:shop.shopName,
						platform:TypeOptions.find(type=>type.label==item||type.value == item).value
					}
					shops.push(obj)
				})
				let bills = Object.values(billObj)
				try {
					await importToSys(shops,bills,shop.orderList,{hideErrLog:true})
					shop.isClick = true
				} catch (error) {
					console.log(error)
					this.errlogs.push(shop.shopName+":"+error.message || error)
				}
			}			
		},
		batchAdd(){
			console.log("添加")
			this.$confirm("将导入当前订单到系统，是否继续", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(async () => {
				await this.batchImport()
				success("已完成一键导入,请检查有无错误项")
			})
		},
		batchChange(){
			this.$refs.batchChangeRef.submit((form)=>{
				let ref = this.$refs.pt
				console.log(ref.checkboxSelected)
				let checked = ref.checkboxSelected
				let arrIndex = []
				checked.forEach(item=>{
					let index = this.shopArrs.findIndex(shop=>shop.shopName == item.shopName)
					if(index==-1){
						this.errlogs.push(`勾选店铺未找到：${item.shopName}`)
					}else{
						arrIndex.push(index)
					}
				})
				console.log(arrIndex)
				for(let i=0;i<arrIndex.length;i++){
					this.shopArrs[arrIndex[i]].orderList = this.shopArrs[arrIndex[i]].orderList.map(item=>{
						return {
							...item,
							money:NP.plus(item.money,form.price)
						}
					})
				}
				this.updateCount()
				this.batchChangePriceForm = {
					price:""
				}
				this.showBatchChange = false
			})
			
		},
		selectChange(val){
			if(val.length>0){
				this.checkBoxNoChange = false
			}else{
				this.checkBoxNoChange = true
			}
		},
		dbclick(row){
			row.isEdit = true
			this.currentEditShopName = row.shopName
			this.$nextTick(()=>{
				this.$refs.shopNameEdit.focus()
			})
		},
		cancelEditShopName(row){
			row.isEdit = false
		},
		confirmEdit(row){
			console.log("change-----")
			this.importArrs = this.shopArrs.reduce((current,next)=>{
				return current.concat(next.orderList)
			},[])
			console.log(this.importArrs)
			this.importArrs = this.importArrs.map(item=>{
				return {
					...item,
					shopName:item.shopName==row.shopName?this.currentEditShopName:item.shopName
				}
			})
			this.filterData()
			row.isEdit = false
			this.currentEditShopName = ""
		},
		async changePrice(index){
			// console.log(this.$refs.changPrice)
			let copm = this.$refs.changPrice
			console.log(copm,index)
			console.log(this)
			// let valid = await copm[index].validate()
			// console.log(valid)
			// if(valid){
			let form = this.changeForm[index]
			let pass = 0
			//改价，等于form.price1 的改成 form.price
			this.shopArrs[this.currentShop].orderList = this.shopArrs[this.currentShop].orderList.map(item=>{
				Number(item.money) == Number(form.price1) && pass++
				return {
					...item,
					money:Number(item.money)==Number(form.price1)?form.price2:item.money
				}
			})
			if(pass==0){
				this.$message.error(`未找到与 ${form.price1} 匹配的金额`)
				return
			}
			this.updateCount()
			this.$refs.pt.tableData = this.shopArrs
			// this.visible = false
			let prices = Array.from(this.shopArrs[this.currentShop].prices)
			this.changeForm = prices.map(item=>{
				return {
					price1:item,
					price2:null
				}
			})
			// }
			if(index==copm.length-1){
				this.visible = false
			}else{
				this.$refs.price2[index+1].focus()
			}
		},
	},
	computed:{
		title(){
			return "批量改价--"+ this.shopArrs[this.currentShop]?.shopName
		},
		errorLogString(){
			return this.errlogs.join("<br />")
		},
		afterParse(){
			return this.shopArrs.reduce((current,next)=>{
				let i = 0
				let total = next.orderList.reduce((c,n)=>{
					i++
					return NP.plus(c,n.money)
				},0)
				return {
					totalPrice:NP.plus(current.totalPrice,total),
					orderCount:NP.plus(current.orderCount,i)
				}
			},{
				totalPrice:0,
				orderCount:0
			})
		}
	},
	watch:{
		status(newval,oldval){
			if(newval==1){
				let pt = this.$refs.pt
				this.updateCount()
				pt.tableData = this.shopArrs
				pt.columns = columns["shop"]
			}else if(newval == 2){
				let pt = this.$refs.pt
				pt.tableData = this.shopArrs[this.currentShop].orderList
				pt.columns = columns["order"]
			}else if(newval == 0){
				this.importArrs = []
				this.hasFile = false
				this.errlogs = []
			}
		}
	}
}
</script>
<style scoped lang="less">
.orderText{
	display: flex;
	position: relative;
	padding-left: 15px;
	font-size: 18px;
	width: 100px;
	box-sizing: border-box;
}
.orderText::before{
	display: block;
	content: "";
	border-width: 0px;
	position: absolute;
	left: 0px;
	top: 50%;
	transform: translateY(-50%);
	width: 6px;
	height: 20px;
	background: inherit;
	background-color: rgba(37, 97, 239, 1);
	border-radius: 8px;;
}
.main{
    background-color: #FFF;
}
.file-upload-container{
    // position: absolute;
    // left: 35%;
    // top: 10%;
    // padding: 20px;
    // margin-right: 20px;
    display: flex;
    justify-content: center;
    .begin-btn{
        margin-left: 20px;
    }
}
/deep/ .el-upload-list{
    max-height: 60%;
    overflow: auto;
}
.expand-img-container{
	display: flex;
	padding: 0 0 0 100px;
	img{
		margin-right: 20px;
	}
}
.errorLogString{
	color: #999;
	font-size: 14px;
}
</style>